#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import os
import sys
import logging
import threading


from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Server, Shell

from Ump.objs.license.manager import LicenseManager
from Ump.common.log import init_info_logger
from Ump.common.wsgilog import WsgiLog, LogStdout
from Ump.objs.db import models
from Ump.schedule import main as schedule_main

import utils
import defs

LOG = init_info_logger()

from Ump import create_app, db


#@app.teardown_request
#def teardown_request(*args, **kwargs):
#    db.session.remove()

class MyWsgiLog(WsgiLog):

    def __init__(self, application):
        WsgiLog.__init__(self,
                        application,
                        logformat = '%(asctime)s-%(message)s',
                        tofile = True,
                        toprint = True,
                        file = defs.CONTROLLER_SERVER_LOG_PATH,
                        MAXBYTES = 1024000 * 20, 
                        BACKUPCOUNT = 5
                        )   
        sys.stdout = LogStdout(self.logger, logging.INFO)
        sys.stderr = LogStdout(self.logger, logging.ERROR)


def init_service(port=None, is_log=True, app=None):

    from Ump.objs.db.session import init_db_session
    init_db_session(db)

    LOG.info("Listening http://0.0.0.0:%s/" % port)
    restart_ws_cmd = 'python %s/websocket/ws_server_daemon.py --stop;\
                    python %s/websocket/ws_server_daemon.py --start' % (utils.ump_home, utils.ump_home)
    print restart_ws_cmd
    os.system(restart_ws_cmd)

    with app.app_context():
        cluster = models.Cluster.query.first()
        from Ump.objs import root
        root.init_root(cluster)

        #start controller auto sync license 
    #    utils.exception_pass(LicenseManager().fusionnas_license_sync, is_ssh_runner=True)
        
        _scheduler = schedule_main.init_scheduler(app)
        _scheduler.start_in_thread()


def main(port=None, is_log=True):
    app, db = create_app('default')
    migrate = Migrate(app, db)
    manager = Manager(app)

    init_service(app=app, port=port)

    port = port or defs.CONTROLLER_PORT 

    print "Listening http://0.0.0.0:%s/" % port
    if is_log:
        app.wsgi_app = MyWsgiLog(app.wsgi_app)

    app.run(host="0.0.0.0", port=port)


def debug():
    from Ump.objs.db.models import Host, User

    app, db = create_app('default')
    migrate = Migrate(app, db)
    manager = Manager(app)
    from Ump.objs.db.session import init_db_session
    init_db_session(db)

    def make_shell_context():
        return dict(app=app, db=db, Host=Host, User=User)

    manager.add_command('db', MigrateCommand)
    manager.add_command("shell", Shell(make_context=make_shell_context))
    manager.add_command("runserver", Server(host="0.0.0.0", port=defs.CONTROLLER_PORT, use_debugger=True, use_reloader=True))

    # init_service()
    manager.run()


if __name__ == "__main__":
    debug()
